/*
 * Copyright (c) 2017 Qunar.com. All Rights Reserved.
 */
package com.guoyu.project.common.freemarker;

import java.io.IOException;
import java.util.Map;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * @author: libo Date: 17-3-1 Time: 上午11:00
 * @version: \$Id$
 */
public class BlockDirective implements TemplateDirectiveModel {

    /**
     * 定义块，标签名称
     */
    private final static String BLOCK_TAG = "block";

    @Override
    public void execute(Environment env, Map params, TemplateModel[] templateModels, TemplateDirectiveBody body)
            throws TemplateException, IOException {
        String name = FreemarkerSupports.getRequiredArgument(params, "name");
        OverrideBodyWrapper overrideBody = FreemarkerSupports.getOverrideBody(env, name);
        if (overrideBody == null) {
            if (body != null) {
                body.render(env.getOut());
            }
        } else {
            FreemarkerSupports.setParentForTop(new OverrideBodyWrapper(body, env), overrideBody);
            overrideBody.render(env.getOut());
        }
    }

}
